﻿using AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using GoodAdmin.Core;
using Tea;

namespace GoodAdmin.AuthExtra;

public class DingToken(IRedisCacheManager redisCacheManager): ITransient
{
    private readonly IRedisCacheManager redisCacheManager = redisCacheManager;
    public async Task<string> GetAccessToken()
    {
        var token = redisCacheManager.Get<string>("dingdingAccessToken");
        if (string.IsNullOrWhiteSpace(token))
        {
            token = await GetDingdingAccessToken();
        }
        return token;
    }

    private static AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client CreateAuthClient()
    {
        AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
        config.Protocol = "https";
        config.RegionId = "central";
        return new AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client(config);
    }

    private async Task<string> GetDingdingAccessToken()
    {
        AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client client = CreateAuthClient();
        GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest
        {
            AppKey = "dingdbosuyxvfdf2sydl",
            AppSecret = "lYTAkNf06_ILsdJSZaLP6y9lPo30eF8-bgZp5gjQ25tgsmtC6UDo7ODfyozwU1kE",
        };
        try
        {
            GetAccessTokenResponse? res = await client.GetAccessTokenAsync(getAccessTokenRequest);
            var timeSpan = TimeSpan.FromSeconds(res.Body.ExpireIn.ToDouble());
            redisCacheManager.Set("dingdingAccessToken", res.Body.AccessToken, timeSpan);
            return res.Body.AccessToken;
        }
        catch (TeaException err)
        {
            if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
            {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw Oops.Bah(err.Message);
            }
        }
        catch (Exception _err)
        {
            TeaException err = new TeaException(new Dictionary<string, object>
        {
            { "message", _err.Message }
        });
            if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
            {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw Oops.Bah(err.Message);
            }
        }
        throw Oops.Bah("未获取到token");
    }
}
